package com.epfresh.api.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.aigestudio.wheelpicker.core.AbstractWheelDecor;
import com.aigestudio.wheelpicker.core.AbstractWheelPicker;
import com.aigestudio.wheelpicker.core.IWheelPicker;
import com.aigestudio.wheelpicker.view.WheelCrossPicker;
import com.aigestudio.wheelpicker.view.WheelStraightPicker;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.CityAddressList;
import com.epfresh.api.utils.L;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TimePickerDialog extends Dialog implements View.OnClickListener {

    String[] months_big = { "1", "3", "5", "7", "8", "10", "12" };
    String[] months_little = { "4", "6", "9", "11" };

    final List<String> list_big = Arrays.asList(months_big);
    final List<String> list_little = Arrays.asList(months_little);

    private View root;
    private ViewGroup container;
    private Button rButton, lButton;
    private IWheelPicker picker;

    private int index1;
    private int index2;
    private int index3;
    private String data1;
    private String data2;
    private String data3;

    private WheelStraightPicker wheelUnit1;
    private WheelStraightPicker wheelUnit2;
    private WheelStraightPicker wheelUnit3;

    private OnPositiveClickListener onPositiveClickListener;
    private Context mContext;
    private boolean isFirst;

    private int startYear = 1991;
    private int startMonth = 1;
    private int startDay = 1;

    private int endYear = 2100;
    private int endMonth = 12;
    private int endDay = 31;
    private int cYear;
    private int cMonth;
    private int cDay;
    protected float labelTextSize;
    private List<String> years = new ArrayList<>();
    protected int labelColor = 0xFF333333;

    public TimePickerDialog(Context context) {
        super(context);
        mContext = context;
        padding = mContext.getResources().getDimensionPixelSize(R.dimen.WheelPadding);
        textSize = mContext.getResources().getDimensionPixelSize(R.dimen.TextSizeLarge);
        itemSpace = mContext.getResources().getDimensionPixelSize(R.dimen.ItemSpaceLarge);
        labelTextSize = mContext.getResources().getDimensionPixelSize(R.dimen.WheelLabelTextSize);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setCanceledOnTouchOutside(true);


        root = getLayoutInflater().inflate(R.layout.dialog_new_layout, null);
        container = (ViewGroup) root.findViewById(R.id.content);
        container.removeAllViews();
        rButton = (Button) root.findViewById(R.id.positiveButton);
        rButton.setOnClickListener(this);
        lButton = (Button) root.findViewById(R.id.negativeButton);
        lButton.setOnClickListener(this);

        View v = LayoutInflater.from(getContext()).inflate(R.layout.dialog_time, null);
        setContentView(v);

        wheelUnit1 = (WheelStraightPicker) findViewById(R.id.wheel_unit_1);
        wheelUnit2 = (WheelStraightPicker) findViewById(R.id.wheel_unit_2);
        wheelUnit3 = (WheelStraightPicker) findViewById(R.id.wheel_unit_3);

        addLabel(wheelUnit1,"年");
        addLabel(wheelUnit2,"月");
        addLabel(wheelUnit3,"日");

    }

    public void setYear(int type,int currentYear ,int currentMonth,int currentDay,int startMonth,int endMonth,int startDay,int endDay){
        years = initYear(startYear, endYear);
        int y = currentYear - startYear;
        if (y < 0){
            y = 0;
        }
        if (currentYear -endYear >0){
            y = 0;
        }
        if (type == 0) {
            L.d("years:","years:"+years);
            L.d("years:","yearscurrent:"+y);
            index1 = y;
            wheelUnit1.setData(years,y);
        }
        List<String> months = initMonth(startMonth, endMonth);
        int cm = 0;
        for (int j=0;j<months.size();j++){
            String s = months.get(j);
            L.d("months:","s:"+s+"-"+currentMonth);

            if ( Integer.valueOf(s) == currentMonth){
                cm = j;
                break;
            }
        }
        if (type == 1 || type == 0) {
            wheelUnit2.setData(months,cm);
            index2 = cm;
            L.d("months:","months:"+months);
            L.d("months:","monthscurrent:"+cm);
        }

        List<String> days = initDay(startDay, endDay);
        int d = 0;
        for (int j=0;j<days.size();j++){
            String s = days.get(j);
            if (Integer.valueOf(s) == currentDay){
                d = j;
                break;
            }
        }
        wheelUnit3.setData(days,d);
        index3 = d;
        L.d("days:","days:"+days);
        L.d("days:","dayscurrent:"+d);
    }
    public List<String> initYear(int startYear,int endYear){
        List<String> years = new ArrayList<>();
        for (int i=startYear;i<=endYear;i++){
            years.add(i+"");
        }
        return years;
    }
    public List<String> initMonth(int startMonth,int endMonth){
        List<String> month = new ArrayList<>();
        for (int i=startMonth;i<=endMonth;i++){
            if (i <10){
                month.add("0"+i);
            }else {
                month.add(i+"");

            }
        }
        return  month;
    }
    public List<String> initDay(int startDay,int endDay){
        List<String> day = new ArrayList<>();
        for (int i=startDay;i<=endDay;i++){
            if (i <10){
                day.add("0"+i);
            }else {
                day.add(i+"");

            }
        }
        return  day;
    }


    //    public int calMonth(int currentYear,int oldMonth){
//        int m = 1;
//
//        int minMonth = 1;
//        int maxMonth = 12;
//        if (currentYear == startYear){
//            if (oldMonth < startMonth){
//                m = startMonth;
//            }else {
//                m = oldMonth;
//            }
//        }else if(currentYear == endYear){
//            if (oldMonth > endMonth){
//                m = endMonth;
//            }else {
//                m = oldMonth;
//            }
//        }else {
//            m = oldMonth;
//        }
//
//        return m;
//    }
    public void setData(int currentYear , int currentMonth, int currentDay) {

        isFirst = true;

        cYear = currentYear;
        cMonth = currentMonth;
        cDay = currentDay;

        int minM = 1;
        int maxM = 12;
        int minD = 1;
        int maxD = 31;
        if (currentYear == startYear){
            minM = startMonth;
            if (currentMonth < startMonth){
                currentMonth = startMonth;
            }
        }
        if (currentYear == endYear){
            maxM = endMonth;
            if (currentMonth > endMonth){
                currentMonth = endMonth;
            }
        }



//        int minDay = 1;
//        int maxDay = 31;
//        int oldDay = Integer.valueOf(data3);
        //大月
        if (list_big.contains(currentMonth+"")){
            maxD = 31;
        }else if (list_little.contains(currentMonth+"")){
            //小月
            maxD = 30;
        }else {
            if ((currentYear % 4 == 0 && currentYear % 100 != 0)
                    || currentYear % 400 == 0){

                maxD = 29;
            }
            else{
                maxD = 28;
            }
        }


        if (currentYear == startYear && currentMonth ==startMonth){
            minD = startDay;
            if (currentDay < startDay){
                currentDay = startDay;
            }
        }
        if(currentYear == endYear && currentMonth ==endMonth){
            maxD = endDay;
            if (currentDay > endDay){
                currentDay = endDay;
            }
        }
        L.d("currenttime","currenttime:"+currentYear+"-"+currentMonth+"-"+currentDay);

        L.d("currenttime","rang_month:"+"-month:"+minM+"-"+maxM);
        L.d("currenttime","rang_month:"+"-day:"+minD+"-"+maxD);
        L.d("currenttime","rang_month_1:"+startMonth+"-"+endMonth);
        L.d("currenttime","rang_day_1:"+startDay+"-"+endDay);
        setYear(0,currentYear,currentMonth,currentDay,minM,maxM,minD,maxD);

        wheelUnit1.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolling(float deltaX, float deltaY) {

            }

            @Override
            public void onWheelSelected(int index, String data) {
                data1 = data;

                if (!isFirst) {
                    TimePickerDialog.this.index1 = index;
//                    TimeDialog.this.index2 = 0;
//                    TimeDialog.this.index3 = 0;
                    Integer year = Integer.valueOf(data);

                    int oldMonth = Integer.valueOf(data2);
                    int m = oldMonth;
                    int minMonth = 1;
                    int maxMonth = 12;
                    if (year == startYear){
                        minMonth = startMonth;
                        if (oldMonth < startMonth){
                            m = startMonth;
                        }
                    }
                    if(year == endYear){
                        maxMonth = endMonth;
                        if (oldMonth > endMonth){
                            m = endMonth;
                        }
                    }
                    //fix bug
                    if (m < 10) {
                        data2 = "0"+m ;
                    }else {
                        data2 = m + "";

                    }
                    int minDay = 1;
                    int maxDay = 31;
                    int oldDay = Integer.valueOf(data3);
                    //大月
                    if (list_big.contains(m+"")){
                        maxDay = 31;
                    }else if (list_little.contains(m+"")){
                        //小月
                        maxDay = 30;
                    }else {
                        if ((year % 4 == 0 && year % 100 != 0)
                                || year % 400 == 0){

                            maxDay = 29;
                        }
                        else{
                            maxDay = 28;
                        }
                    }

                    int d = oldDay;
                    if (year == startYear && m ==startMonth){
                        minDay = startDay;
                        if (oldDay < startDay){
                            d = startDay;
                        }
                    }
                    if(year == endYear && m ==endMonth){
                        maxDay = endDay;
                        if (oldDay > endDay){
                            d = endDay;
                        }
                    }

                    //fix bug
                    if (d < 10 ){
                        data3 = "0"+d;
                    }else {
                        data3 = d + "";
                    }
                    L.d("currenttime","currenttime_year:"+year+"-"+m+"-"+d);
                    L.d("currenttime","rang_year:"+minMonth+"-"+maxMonth+"-day:"+minDay+"-"+maxDay);
                    L.d("currenttime","rang_year_1:"+startDay+"-"+endDay);
                    setYear(1,year,m,d,minMonth,maxMonth,minDay,maxDay);


                }

            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });
        wheelUnit2.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolling(float deltaX, float deltaY) {

            }

            @Override
            public void onWheelSelected(int index, String data) {
                data2 = data;
                if (!isFirst) {
                    TimePickerDialog.this.index2 = index;
                    int minDay = 1;
                    int maxDay = 31;
                    int oldDay = Integer.valueOf(data3);

                    int year = Integer.valueOf(data1);
                    int m = Integer.valueOf(data2);
                    //大月
                    if (list_big.contains(m+"")){
                        maxDay = 31;
                    }else if (list_little.contains(m+"")){
                        //小月
                        maxDay = 30;
                    }else {
                        if ((year % 4 == 0 && year % 100 != 0)
                                || year % 400 == 0){

                            maxDay = 29;
                        }
                        else{
                            maxDay = 28;
                        }
                    }

                    int d = oldDay;
                    if (year == startYear && m ==startMonth){
                        minDay = startDay;
                        if (oldDay < startDay){
                            d = startDay;
                        }
                    }
                    if(year == endYear && m ==endMonth){
                        maxDay = endDay;
                        if (oldDay > endDay){
                            d = endDay;
                        }
                    }


                    if (m <10){
                        data2 = "0"+m;
                    }else {
                        data2 = m +"";
                    }
                    if (d < 10){
                        data3 = "0"+d;
                    }else {
                        data3 = d + "";
                    }
                    L.d("currenttime","currenttime_year:"+year+"-"+m+"-"+d);
                    L.d("currenttime","rang_month:"+"-day:"+minDay+"-"+maxDay);
                    L.d("currenttime","rang_month_1:"+startDay+"-"+endDay);
                    setYear(2,year,m,d,1,12,minDay,maxDay);

                }
                isFirst = false;
            }

            @Override
            public void onWheelScrollStateChanged(int state) {

                isFirst = false;
            }
        });
        wheelUnit3.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolling(float deltaX, float deltaY) {

            }

            @Override
            public void onWheelSelected(int index, String data) {
                data3 = data;
                TimePickerDialog.this.index3 = index;
            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });

    }


    public List<String> getCityList(ArrayList<CityAddressList> citys) {
        List<String> list1 = new ArrayList<>();
        for (int i = 0; i < citys.size(); i++) {
            list1.add(citys.get(i).getName());
        }

        return list1;
    }

    @Override
    public void setContentView(View view) {
        container.addView(view);
        super.setContentView(root);
//        Window dialogWindow = getWindow();
//        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//        lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS;
//        dialogWindow.setAttributes(lp);
    }

    private void addLabel(WheelCrossPicker picker, final String label) {
        picker.setWheelDecor(true, new AbstractWheelDecor() {
            @Override
            public void drawDecor(Canvas canvas, Rect rectLast, Rect rectNext, Paint paint) {
                paint.setColor(labelColor);
                paint.setTextAlign(Paint.Align.CENTER);
                paint.setTextSize(labelTextSize * 1.5F);
                canvas.drawText(label, rectNext.centerX(),
                        rectNext.centerY() - (paint.ascent() + paint.descent()) / 2.0F, paint);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.positiveButton:

                if (isPositiveDismiss)
                    dismiss();
                if (onPositiveClickListener != null){
                    Log.e("time","date:"+data1+"-"+data2+"-"+data3);
                    onPositiveClickListener.onPositiveClickListener(0,data1+"-"+data2+"-"+data3);
                }
                break;
            case R.id.negativeButton:
                dismiss();
                break;
        }
    }


    public OnPositiveClickListener getOnPositiveClickListener() {
        return onPositiveClickListener;
    }

    public void setOnPositiveClickListener(OnPositiveClickListener onPositiveClickListener) {
        this.onPositiveClickListener = onPositiveClickListener;
    }

    public void setTitle(String title) {
        ((TextView) root.findViewById(R.id.title)).setText(title);
    }

    public void setLeftText(String text) {
        ((TextView) root.findViewById(R.id.negativeButton)).setText(text);
    }

    public void setRightText(String text) {
        ((TextView) root.findViewById(R.id.positiveButton)).setText(text);
    }

    public boolean isPositiveDismiss() {
        return isPositiveDismiss;
    }

    public void setPositiveDismiss(boolean positiveDismiss) {
        isPositiveDismiss = positiveDismiss;
    }

    public void setCurrentItem(int index1, int index2) {
        wheelUnit1.setItemIndex(index1);
        wheelUnit2.setItemIndex(index2);
    }

    private boolean isPositiveDismiss = true;


    private int padding;
    private int textSize;
    private int itemSpace;


    public interface OnPositiveClickListener{
        public void onPositiveClickListener(int index1,String data);
    }

    public int getStartYear() {
        return startYear;
    }

    public void setStartYear(int startYear) {
        this.startYear = startYear;
    }

    public int getStartMonth() {
        return startMonth;
    }

    public void setStartMonth(int startMonth) {
        this.startMonth = startMonth;
    }

    public int getStartDay() {
        return startDay;
    }

    public void setStartDay(int startDay) {
        this.startDay = startDay;
    }

    public int getEndYear() {
        return endYear;
    }

    public void setEndYear(int endYear) {
        this.endYear = endYear;
    }

    public int getEndMonth() {
        return endMonth;
    }

    public void setEndMonth(int endMonth) {
        this.endMonth = endMonth;
    }

    public int getEndDay() {
        return endDay;
    }

    public void setEndDay(int endDay) {
        this.endDay = endDay;
    }



    public void setCurrentDate(String time){
        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            if (time == null ||"".equals(time)){

                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH)+1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                setData(year,month,day);
            }else {
                date = fmt.parse(time);
                Calendar calendar = Calendar.getInstance();
                if (date == null)
                    calendar.setTimeInMillis(System.currentTimeMillis());
                else
                    calendar.setTime(date);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH)+1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                setData(year,month,day);

                L.d("time:","day:"+year+"-"+month+"-"+day);
            }

        } catch (ParseException e) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH)+1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            setData(year,month,day);
            e.printStackTrace();
        }

    }
}